<template>
  <view class="change-phone-container">
    <view class="header">
      <view class="back" @tap="navigateBack">
        <text class="icon">←</text>
      </view>
      <text class="title">修改手机号</text>
      <view class="placeholder"></view>
    </view>

    <view class="form-container">
      <view class="form-item">
        <text class="label">当前手机号</text>
        <view class="phone-info">
          <text class="current-phone">{{ formatPhone(currentPhone) }}</text>
        </view>
      </view>

      <view class="form-item">
        <text class="label">新手机号</text>
        <input class="input" type="number" placeholder="请输入新手机号" maxlength="11" v-model="newPhone" />
      </view>

      <view class="form-item">
        <text class="label">验证码</text>
        <view class="verification-code">
          <input class="input code-input" type="number" placeholder="请输入验证码" maxlength="6" v-model="verificationCode" />
          <button class="code-btn" @tap="sendVerificationCode" :disabled="isCountingDown || !isValidPhone(newPhone)">
            {{ isCountingDown ? `${countdown}秒后重发` : '获取验证码' }}
          </button>
        </view>
      </view>

      <button class="confirm-btn" @tap="changePhone" :disabled="!newPhone || !verificationCode || !isValidPhone(newPhone)">确认修改</button>
    </view>
  </view>
</template>

<script>
import { request } from '@/utils/request.js';

export default {
  data() {
    return {
      currentPhone: '', // 当前绑定的手机号
      newPhone: '',
      verificationCode: '',
      isCountingDown: false,
      countdown: 60,
      countdownTimer: null
    };
  },
  onLoad() {
    // 获取当前绑定的手机号
    this.getCurrentPhone();
  },
  onUnload() {
    // 清除定时器
    if (this.countdownTimer) {
      clearInterval(this.countdownTimer);
    }
  },
  methods: {
    // 返回上一页
    navigateBack() {
      uni.navigateBack();
    },

    // 获取当前绑定的手机号
    async getCurrentPhone() {
      try {
        const res = await request({
          url: 'user/getUserInfo',
          showLoading: true
        });

        if (res.code === 200 && res.data && res.data.phone) {
          this.currentPhone = res.data.phone;
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
        uni.showToast({ title: '获取用户信息失败', icon: 'none' });
      }
    },

    // 验证手机号格式
    isValidPhone(phone) {
      return /^1[3-9]\d{9}$/.test(phone);
    },

    // 格式化手机号（中间四位用*代替）
    formatPhone(phone) {
      if (!phone) return '';
      return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
    },

    // 发送验证码
    async sendVerificationCode() {
      if (!this.newPhone) {
        uni.showToast({ title: '请输入新手机号', icon: 'none' });
        return;
      }

      if (!this.isValidPhone(this.newPhone)) {
        uni.showToast({ title: '请输入正确的手机号', icon: 'none' });
        return;
      }

      if (this.newPhone === this.currentPhone) {
        uni.showToast({ title: '新手机号不能与当前手机号相同', icon: 'none' });
        return;
      }

      try {
        // 调用发送验证码API
        const res = await request({
          url: 'user/sendVerificationCode',
          data: {
            phone: this.newPhone,
            type: 'changePhone' // 验证码类型：修改手机号
          },
          showLoading: true
        });

        if (res.code === 200) {
          uni.showToast({ title: '验证码发送成功', icon: 'success' });
          this.startCountdown();
        } else {
          uni.showToast({ title: res.msg || '验证码发送失败', icon: 'none' });
        }
      } catch (error) {
        console.error('发送验证码失败:', error);
        uni.showToast({ title: '验证码发送失败，请重试', icon: 'none' });
      }
    },

    // 开始倒计时
    startCountdown() {
      this.isCountingDown = true;
      this.countdown = 60;

      if (this.countdownTimer) {
        clearInterval(this.countdownTimer);
      }

      this.countdownTimer = setInterval(() => {
        if (this.countdown <= 1) {
          clearInterval(this.countdownTimer);
          this.isCountingDown = false;
          this.countdown = 60;
        } else {
          this.countdown--;
        }
      }, 1000);
    },

    // 修改手机号
    async changePhone() {
      if (!this.newPhone) {
        uni.showToast({ title: '请输入新手机号', icon: 'none' });
        return;
      }

      if (!this.isValidPhone(this.newPhone)) {
        uni.showToast({ title: '请输入正确的手机号', icon: 'none' });
        return;
      }

      if (!this.verificationCode) {
        uni.showToast({ title: '请输入验证码', icon: 'none' });
        return;
      }

      try {
        // 调用修改手机号API
        const res = await request({
          url: 'user/changePhone',
          data: {
            newPhone: this.newPhone,
            verificationCode: this.verificationCode
          },
          showLoading: true
        });

        if (res.code === 200) {
          uni.showToast({ title: '手机号修改成功', icon: 'success' });

          // 清除表单
          this.newPhone = '';
          this.verificationCode = '';

          // 更新当前手机号
          this.currentPhone = this.newPhone;

          // 返回上一页
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } else {
          uni.showToast({ title: res.msg || '手机号修改失败', icon: 'none' });
        }
      } catch (error) {
        console.error('修改手机号失败:', error);
        uni.showToast({ title: '手机号修改失败，请重试', icon: 'none' });
      }
    }
  }
};
</script>

<style scoped>
.change-phone-container {
  padding: 0;
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f8f8f8;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 88rpx;
  padding: 0 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #e5e5e5;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 99;
}

.back {
  width: 40rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.icon {
  font-size: 32rpx;
  color: #333;
}

.title {
  font-size: 36rpx;
  color: #333;
  font-weight: 500;
}

.placeholder {
  width: 40rpx;
}

.form-container {
  padding: 40rpx;
  margin-top: 100rpx;
  flex: 1;
}

.form-item {
  margin-bottom: 30rpx;
}

.label {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 10rpx;
  display: block;
}

.input {
  width: 100%;
  height: 90rpx;
  background-color: #fff;
  border-radius: 10rpx;
  padding: 0 30rpx;
  font-size: 32rpx;
  box-sizing: border-box;
  border: 1rpx solid #e5e5e5;
}

.phone-info {
  height: 90rpx;
  background-color: #fff;
  border-radius: 10rpx;
  padding: 0 30rpx;
  font-size: 32rpx;
  box-sizing: border-box;
  border: 1rpx solid #e5e5e5;
  display: flex;
  align-items: center;
}

.current-phone {
  color: #999;
}

.verification-code {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.code-input {
  flex: 1;
}

.code-btn {
  width: 220rpx;
  height: 90rpx;
  background-color: #409eff;
  color: #fff;
  font-size: 28rpx;
  border-radius: 10rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.code-btn:disabled {
  background-color: #ccc;
  color: #fff;
}

.confirm-btn {
  width: 100%;
  height: 90rpx;
  background-color: #409eff;
  color: #fff;
  font-size: 32rpx;
  border-radius: 10rpx;
  margin-top: 60rpx;
}

.confirm-btn:disabled {
  background-color: #ccc;
}
</style>
